package org.me.runaway;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import com.google.android.maps.GeoPoint;


public class PlaceList extends ListActivity {

    private static final String GO_MAP_OPTION = "Navegar no Mapa";
    private static final String CALL_NUMBER1_OPTION = "Ligar para ";
    private static final String CALL_NUMBER2_OPTION = "Ligar para ";
    private static final String SHOW_PLACE_OPTION = "Mostrar Localização no mapa";
    private static final String SHOW_ROUTE_OPTION = "Mostrar Rota até à Localização";
    private static final String DELETE_FAVORITE_OPTION = "Eliminar dos Favoritos";
    SimpleCursorAdapter myAdapter;
    Cursor cursor;
    DB_Adapter db = null;

    Intent details;
    Intent map;
    Bundle extras;
    int option;


    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        setContentView(R.layout.list);

        db = new DB_Adapter(this.getApplicationContext());

        extras = getIntent().getExtras();

        if (extras != null) {
            if (extras.containsKey("option")) {
                option = extras.getInt("option");
                switch (option) {
                    case 0:
                        searchByRestaurant(extras.getString("name"));
                        break;
                    case 1:
                        searchByHotel(extras.getString("name"));
                        break;
                    case 2:
                        searchByMuseum(extras.getString("name"));
                        break;
                    case 3:
                        searchByTwoTypes(extras.getString("name"), 0);
                        break;
                    case 4:
                        searchByTwoTypes(extras.getString("name"), 1);
                        break;
                    case 5:
                        searchByTwoTypes(extras.getString("name"), 2);
                        break;
                    case 6:
                        if (extras.containsKey("all") && extras.getBoolean("name")) {
                            searchAll();
                        } else if (extras.containsKey("name") && extras.getString("name") != null) {
                            searchByName(extras.getString("name"));
                        } else {
                            searchAll();
                        }
                        break;
                }
            } else if (extras.getBoolean("favorites") == true) {
                db.open();
                cursor = db.queryFavorites();

                myAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor,
                        new String[]{Place.KEY_NAME, Place.KEY_TYPE},
                        new int[]{R.id.name, R.id.type});

                setListAdapter(myAdapter);
                startManagingCursor(cursor);
                db.close();
            }
        }

        registerForContextMenu(getListView());
    }

    @Override
    public void onListItemClick(ListView parent, View v, int position, long id) {
        super.onListItemClick(parent, v, position, id);

        showDetails();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, GO_MAP_OPTION).setIcon(R.drawable.world);
        menu.add(0, 1, 0, MainActivity.EXIT_OPTION).setIcon(R.drawable.logout);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0:
                map = new Intent(this, MainActivity.class);
                map.putExtra("id", "myLocation");
                startActivity(map);
                this.finish();
                return true;
            case 1:
                this.finish();
                return true;
        }

        return false;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, 0, 0, SHOW_PLACE_OPTION);
        menu.add(0, 1, 0, SHOW_ROUTE_OPTION);
        if (cursor.getString(cursor.getColumnIndex(Place.KEY_CONTACT1)).length() > 1) {
            menu.add(0, 2, 0, CALL_NUMBER1_OPTION + cursor.getString(cursor.getColumnIndex(Place.KEY_CONTACT1)));
        } else {
            menu.add(0, 2, 0, CALL_NUMBER1_OPTION + cursor.getString(cursor.getColumnIndex(Place.KEY_CONTACT1))).setVisible(false);
        }
        if (cursor.getString(cursor.getColumnIndex(Place.KEY_CONTACT2)).length() > 1) {
            menu.add(0, 3, 0, CALL_NUMBER2_OPTION + cursor.getString(cursor.getColumnIndex(Place.KEY_CONTACT2)));
        } else {
            menu.add(0, 3, 0, CALL_NUMBER1_OPTION + cursor.getString(cursor.getColumnIndex(Place.KEY_CONTACT2))).setVisible(false);
        }
        if (extras.containsKey("favorites") && extras.getBoolean("favorites")) {
            menu.add(0, 4, 0, DELETE_FAVORITE_OPTION);
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0:
                String id = cursor.getString(cursor.getColumnIndex(Place.KEY_ROWID));
                map = new Intent(this, MainActivity.class);
                map.putExtra("id", id);
                startActivity(map);
                this.finish();
                break;
            case 1:
                map = new Intent(this, GPS.class);
                StatusGPS.setStatus("route");
                StatusGPS.setToPosition(new GeoPoint((int) (cursor.getDouble(cursor.getColumnIndex(Place.KEY_LAT)) * 1E6), (int) (cursor.getDouble(cursor.getColumnIndex(Place.KEY_LNG)) * 1E6)));

                map.putExtra("name", cursor.getString(cursor.getColumnIndex(Place.KEY_NAME)));

                startActivity(map);
                this.finish();
                break;
            case 2:
                callPhoneNumber(cursor.getString(cursor.getColumnIndex(Place.KEY_CONTACT1)));
                break;
            case 3:
                callPhoneNumber(cursor.getString(cursor.getColumnIndex(Place.KEY_CONTACT2)));
                break;
            case 4:
                if (extras.containsKey("favorites") && extras.getBoolean("favorites")) {
                    db = new DB_Adapter(getBaseContext());
                    db.open();
                    long rowId = cursor.getLong(cursor.getColumnIndex(Place.KEY_ROWID));
                    Cursor cs = db.getPlaceID(rowId);
                    if (cs != null) {
                        cs.moveToFirst();
                        Place p = db.getPlaceFromCursor(cs);
                        p.setFavorite(false);
                        db.updatePlace(rowId, p);
                    }

                    cursor = db.queryFavorites();
                    myAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor,
                            new String[]{Place.KEY_NAME, Place.KEY_TYPE},
                            new int[]{R.id.name, R.id.type});

                    setListAdapter(myAdapter);
                    startManagingCursor(cursor);

                    db.close();
                }
                break;
        }

        return false;
    }

    private void showDetails() {

        details = new Intent(this, PlaceDetails.class);
        details.putExtra(Place.KEY_ROWID, cursor.getLong(cursor.getColumnIndex(Place.KEY_ROWID)));
        details.putExtra(Place.KEY_NAME, cursor.getString(cursor.getColumnIndex(Place.KEY_NAME)));
        details.putExtra(Place.KEY_ADDRESS, cursor.getString(cursor.getColumnIndex(Place.KEY_ADDRESS)));
        details.putExtra(Place.KEY_TYPE, cursor.getString(cursor.getColumnIndex(Place.KEY_TYPE)));
        details.putExtra(Place.KEY_CONTACT1, cursor.getString(cursor.getColumnIndex(Place.KEY_CONTACT1)));
        details.putExtra(Place.KEY_CONTACT2, cursor.getString(cursor.getColumnIndex(Place.KEY_CONTACT2)));
        details.putExtra(Place.KEY_LAT, cursor.getString(cursor.getColumnIndex(Place.KEY_LAT)));
        details.putExtra(Place.KEY_LNG, cursor.getString(cursor.getColumnIndex(Place.KEY_LNG)));
        details.putExtra(Place.KEY_DETAILS, cursor.getString(cursor.getColumnIndex(Place.KEY_DETAILS)));
        details.putExtra(Place.KEY_PRICE, cursor.getString(cursor.getColumnIndex(Place.KEY_PRICE)));
        details.putExtra(Place.KEY_SCHEDULE, cursor.getString(cursor.getColumnIndex(Place.KEY_SCHEDULE)));
        details.putExtra(Place.KEY_RATE, cursor.getString(cursor.getColumnIndex(Place.KEY_RATE)));
        details.putExtra(Place.KEY_TYPE, cursor.getString(cursor.getColumnIndex(Place.KEY_TYPE)));
        details.putExtra(Place.KEY_IMAGE, cursor.getString(cursor.getColumnIndex(Place.KEY_IMAGE)));
        details.putExtra(Place.KEY_FAVORITE, cursor.getString(cursor.getColumnIndex(Place.KEY_FAVORITE)));
        details.putExtra(Place.KEY_VOTED, cursor.getString(cursor.getColumnIndex(Place.KEY_VOTED)));
        startActivity(details);
        this.finish();
    }

    private void callPhoneNumber(String phoneNumber) {
        Intent dial = new Intent(Intent.ACTION_CALL);
        dial.setData(Uri.parse("tel:" + phoneNumber));
        dial.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(dial);
    }

    private void searchAll() {
        db.open();
        cursor = db.getAllPlaces();
        myAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor,
                new String[]{Place.KEY_NAME, Place.KEY_TYPE},
                new int[]{R.id.name, R.id.type});
        setListAdapter(myAdapter);
        startManagingCursor(cursor);
        db.close();
    }

    private void searchByName(String name) {
        db.open();
        cursor = db.querySearch(name);
        myAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor,
                new String[]{Place.KEY_NAME, Place.KEY_TYPE},
                new int[]{R.id.name, R.id.type});

        setListAdapter(myAdapter);
        startManagingCursor(cursor);
        db.close();
    }

    private void searchByRestaurant(String name) {
        db.open();
        cursor = db.querySearchRestaurant(name);
        myAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor,
                new String[]{Place.KEY_NAME, Place.KEY_TYPE},
                new int[]{R.id.name, R.id.type});

        setListAdapter(myAdapter);
        startManagingCursor(cursor);
        db.close();
    }

    private void searchByHotel(String name) {
        db.open();
        cursor = db.querySearchHotel(name);
        myAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor,
                new String[]{Place.KEY_NAME, Place.KEY_TYPE},
                new int[]{R.id.name, R.id.type});
        setListAdapter(myAdapter);
        startManagingCursor(cursor);
        db.close();
    }

    private void searchByMuseum(String name) {
        db.open();
        cursor = db.querySearchMuseum(name);
        myAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor,
                new String[]{Place.KEY_NAME, Place.KEY_TYPE},
                new int[]{R.id.name, R.id.type});

        setListAdapter(myAdapter);
        startManagingCursor(cursor);
        db.close();
    }

    private void searchByTwoTypes(String name, int op) {
        db.open();
        switch (op) {
            case 0:
                cursor = db.querySearchTwoTypes(name, 0);
                myAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor,
                        new String[]{Place.KEY_NAME, Place.KEY_TYPE},
                        new int[]{R.id.name, R.id.type});

                setListAdapter(myAdapter);
                startManagingCursor(cursor);
                break;
            case 1:
                cursor = db.querySearchTwoTypes(name, 1);
                myAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor,
                        new String[]{Place.KEY_NAME, Place.KEY_TYPE},
                        new int[]{R.id.name, R.id.type});

                setListAdapter(myAdapter);
                startManagingCursor(cursor);
                break;
            case 2:
                cursor = db.querySearchTwoTypes(name, 2);
                myAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor,
                        new String[]{Place.KEY_NAME, Place.KEY_TYPE},
                        new int[]{R.id.name, R.id.type});

                setListAdapter(myAdapter);
                startManagingCursor(cursor);
                break;
        }
        db.close();
    }
}
